package com.janlei.pool.thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class ExecutorsStu {

    final static ExecutorService cache = Executors.newCachedThreadPool();
    final static ExecutorService fix = Executors.newFixedThreadPool(10);
    final static ExecutorService single = Executors.newSingleThreadExecutor();
    final static ExecutorService scheduled = Executors.newScheduledThreadPool(10);
    final static ExecutorService poolExecutor = new ThreadPoolExecutor(10, 20,
            10, TimeUnit.SECONDS,
            new ArrayBlockingQueue(10));

    /**
     * 每个线程休眠时间超过100，会创建100个线程，不会复用
     * <p>
     * 时间 存活时间决定是否有复用线程
     */
    public static void test_cache_thread_pool_executor() {
        execute(cache);
    }

    /**
     * 只会在10个核心线程中执行，未执行的放入一个无界队列
     */
    public static void test_fix_thread_pool_executor() {
        execute(fix);
    }

    public static void test_single_thread_pool_executor() {
        execute(single);
    }

    public static void test_scheduled_thread_pool_executor() {
        execute(scheduled);
    }

    public static void test_thread_pool_executor() {
        execute(poolExecutor);
    }

    private static void execute(ExecutorService executorService) {
        for (int i = 1; i <= 100; i++) {
            executorService.execute(new MyTask(i));
        }
    }

    public static void main(String[] args) {
        test_thread_pool_executor();
    }
}

class MyTask implements Runnable {
    int i;

    public MyTask(int i) {
        this.i = i;
    }

    @Override
    public void run() {
        System.out.println(Thread.currentThread().getName() + "---" + i);
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}